<script lang="ts" setup>
import { ref } from 'vue'
import { GetDrawrecordData, GetExcelData } from '@/api/modules/drawactuser'
import { GetOptionData } from '@/api/modules/drawact'
import storage from '@/utils/storage'

const route = useRoute()

const findFrom = ref({
  DrawId: route.query.DrawId ? route.query.DrawId : '',
  UserId: route.query.UserId ? route.query.UserId as string : '',
  UserPhone: '',
})
const dataList: any = reactive({
  list: [],
  option: [],
})
const loading = ref(true)
const total = ref(0)
let PageSize = 20

async function GetDataList(PageIndex: number = 1, PageSize: number = 20) {
  const params = {
    PageIndex,
    PageSize,
    ...(findFrom.value.DrawId && ({ DrawId: findFrom.value.DrawId })),
    ...(findFrom.value.UserId && ({ UserId: findFrom.value.UserId })),
    ...(findFrom.value.UserPhone && ({ UserPhone: findFrom.value.UserPhone })),
  }
  await GetDrawrecordData(params).then(async (dataRes: any) => {
    if (dataRes.succeeded) {
      dataList.list = dataRes.data.items
      total.value = dataRes.data.total
      loading.value = false
    }
  })
  loading.value = false
}
// 查询
function Inquire() {
  GetDataList(1, PageSize)
}

// 导出
async function ExportExcel() {
  const params = {
    ...(findFrom.value.DrawId && ({ DrawId: findFrom.value.DrawId })),
    ...(findFrom.value.UserId && ({ UserId: findFrom.value.UserId })),
    ...(findFrom.value.UserPhone && ({ UserPhone: findFrom.value.UserPhone })),
  }
  try {
    const response: any = await GetExcelData(params)
    // console.log(response)

    const a = document.createElement('a')
    const binaryData = []
    binaryData.push(response)
    a.href = window.URL.createObjectURL(
      new Blob(binaryData, {
        type: 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet;chartset=UTF-8',
      }),
    )
    a.download = (storage.local.get('fileName') as string)
    storage.local.remove('fileName')
    a.click()
    URL.revokeObjectURL(a.href)
  }
  catch (error) {
    // 请求失败处理
    console.error(error)
  }
}

// 翻页
function handleSizeChange(val: number) {
  GetDataList(1, val)
  PageSize = val
}
function handleCurrentChange(val: number) {
  GetDataList(val, PageSize)
}

onMounted(async () => {
  try {
    const option: any = await GetOptionData()
    if (option.succeeded) {
      dataList.option = option.data
    }
    await GetDataList()
  }
  catch (error) {
    console.error(error)
  }
})
</script>

<template>
  <div>
    <PageMain>
      <SearchBar :show-toggle="false">
        <div class="header">
          <el-form label-positio="right" label-width="auto">
            <div class="from">
              <el-form-item label="活动选择">
                <el-select v-model="findFrom.DrawId" placeholder="请选择活动ID" style="width: 240px;">
                  <el-option
                    v-for="item in dataList.option"
                    :key="item.drawId"
                    :label="item.drawId"
                    :value="item.drawId"
                  />
                </el-select>
              </el-form-item>
              <el-form-item label="用户ID">
                <el-input v-model="findFrom.UserId" placeholder="请输入用户ID" clearable />
              </el-form-item>
              <el-form-item label="用户手机号">
                <el-input v-model="findFrom.UserPhone" placeholder="请输入用户手机号" clearable />
              </el-form-item>
            </div>
          </el-form>
          <div class="text-right">
            <el-button @click="Inquire">
              查询
            </el-button>
          </div>
        </div>
      </SearchBar>
      <ElDivider border-style="dashed" />
      <div class="mb-5 text-right">
        <el-button type="success" @click="ExportExcel">
          导出抽奖记录
        </el-button>
      </div>
      <el-table v-loading="loading" :data="dataList.list" stripe style="width: 100%;" border>
        <el-table-column align="center" prop="drawId" label="抽奖活动ID" width="120" />
        <el-table-column align="center" prop="fromSubscriberInfo.userId" label="用户ID" width="100" />
        <el-table-column align="center" prop="fromSubscriberInfo" label="用户信息" width="200">
          <template #default="scope">
            <div v-if="!scope.row.fromSubscriberInfo">
              未授权
            </div>
            <div v-else class="user-name">
              <el-avatar :size="40" style="margin-right: 10px;" :src="scope.row.fromSubscriberInfo?.userAvatar" />
              <div>
                <p style="margin: 0;">
                  {{ scope.row.fromSubscriberInfo?.userNickName }}
                </p>
                <span>
                  {{ scope.row.fromSubscriberInfo?.userPhone }}
                </span>
              </div>
            </div>
          </template>
        </el-table-column>
        <el-table-column align="center" prop="fromSubscriberInfo.scOpenId" label="用户OpenId" width="300" />
        <el-table-column align="center" prop="prizeId" label="奖品券ID" width="100" />
        <el-table-column header-align="center" prop="prizeName" label="奖品名称" width="300">
          <template #default="scope">
            <span>
              {{ scope.row.prizeName }}
            </span>
            <span v-if="scope.row.prizeType !== 1 && scope.row.prizeType === 3">
              -- {{ scope.row.amount }}
            </span>
          </template>
        </el-table-column>
        <el-table-column align="center" prop="prizeType" label="奖品类型" width="160">
          <template #default="scope">
            <el-tag v-if="scope.row.prizeType === 1">
              {{ scope.row.ticketType === 1 ? '赠品券'
                : scope.row.ticketType === 2 ? '奖品券' : '未定义' }}
            </el-tag>
            <el-tag v-else>
              {{ scope.row.prizeType === 2 ? '实物'
                : scope.row.prizeType === 3 ? '红包'
                  : scope.row.prizeType === 3 ? '红包' : '未定义' }}
            </el-tag>
          </template>
        </el-table-column>
        <!-- <el-table-column align="center" prop="prizeType" label="红包金额" width="160">
          <template #default="scope">
            <span>
              {{ scope.row.prizeType === 3 ? scope.row.amount : '无' }}
            </span>
          </template>
        </el-table-column> -->
        <el-table-column align="center" prop="prizeStatus" label="是否领取" width="160">
          <template #default="scope">
            <el-tag>
              {{ scope.row.prizeStatus === 0 ? '待领取'
                : scope.row.prizeStatus === 1 ? '已领取'
                  : scope.row.prizeStatus === -1 ? '退款回收' : '未知' }}
            </el-tag>
          </template>
        </el-table-column>
        <el-table-column align="center" prop="isUsed" label="是否使用" width="160">
          <template #default="scope">
            <el-tag>
              {{ scope.row.isUsed ? '已使用' : '未使用' }}
            </el-tag>
          </template>
        </el-table-column>
        <el-table-column align="center" prop="addTime" label="抽奖时间" width="200" />
        <el-table-column align="center" prop="updateTime" label="更新时间" width="200" />
        <el-table-column align="center" prop="awardCode" label="奖品编码" width="300" />
      </el-table>
      <div style="height: 10px;" />
      <el-pagination
        :default-page-size="20"
        :page-sizes="[5, 10, 20, 50, 100]"
        layout="total, sizes, ->, prev, pager, next, jumper"
        :total="total"
        @size-change="handleSizeChange"
        @current-change="handleCurrentChange"
      />
    </PageMain>
  </div>
</template>

<style scoped>
.header {
  display: grid;
  grid-template-columns: 6fr 1fr;

  .from {
    display: grid;
    grid-template-columns: repeat(auto-fill, minmax(300px, 1fr));
    grid-gap: 20px;

    .el-form-item {
      margin-bottom: 0;
    }
  }
}

.user-name {
  display: flex;
  align-items: center;
  justify-content: left;

  div {
    text-align: left;
  }
}
</style>
